package com.deep.bilibili.service;

import com.deep.bilibili.dao.MenuMapper;
import com.deep.bilibili.dao.RoleMenuMapper;
import com.deep.bilibili.entity.Menu;
import com.deep.bilibili.vo.TreeMenu;
import com.deep.bilibili.vo.TreeMenuAllowAccess;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuServiceImpl implements MenuService {

    /**
     * 菜单服务
     */
    @Autowired
    private MenuMapper menuMapper;

    /**
     * 角色菜单关系服务
     */
    @Autowired
    private RoleMenuMapper roleMenuMapper;


    @Cacheable(value = "permissionCache", key = "#uid")
    @Override
    public List<Integer> selectMenuIdsByAdminerId(Integer adminerId) {
        return menuMapper.selectMenuIdsByAdminerId(adminerId);
    }


//    @Cacheable(value = "menuCache", key = "'treeMenu_' + #adminerId")
    @Override
    public List<TreeMenu> selectTreeMenuByAdminerId(Integer adminerId) {
        /**
         * 当前用户二级菜单权限
         */
        List<Integer> menuIds = roleMenuMapper.selectRoleMenuIdsByAdminerId(adminerId);
        return selectTreeMenuByMenuIdsAndPid(menuIds, 0);
    }

    @Override
    public List<TreeMenu> selectTreeMenuByMenuIdsAndPid(final List<Integer> menuIds, Integer pid) {

        List<Menu> Menus = menuMapper.getInSortList(pid, menuIds);
        List<TreeMenu> treeMenus = new ArrayList<TreeMenu>();
        for(Menu Menu : Menus){
            TreeMenu treeMenu = new TreeMenu();
            treeMenu.setMenu(Menu);
            if(Menu.getDeep() < 2){
                treeMenu.setChildren(selectTreeMenuByMenuIdsAndPid(menuIds,Menu.getId()));
            }
            treeMenus.add(treeMenu);
        }
        return treeMenus;
    }


    @Override
    public List<TreeMenuAllowAccess> selectTreeMenuAllowAccessByMenuIdsAndPid(
            final List<Integer> menuIds, Integer pid) {

        List<Menu> Menus = menuMapper.getSortList(pid);

        List<TreeMenuAllowAccess> treeMenuAllowAccesss = new ArrayList<TreeMenuAllowAccess>();
        for(Menu Menu : Menus){
            TreeMenuAllowAccess treeMenuAllowAccess = new TreeMenuAllowAccess();
            treeMenuAllowAccess.setMenu(Menu);
            /**
             * 是否有权限
             */
            if(menuIds.contains(Menu.getId())){
                treeMenuAllowAccess.setAllowAccess(true);
            }
            /**
             * 子节点
             */
            if(Menu.getDeep() < 3){
                treeMenuAllowAccess.setChildren(selectTreeMenuAllowAccessByMenuIdsAndPid(menuIds,Menu.getId()));
            }
            treeMenuAllowAccesss.add(treeMenuAllowAccess);
        }
        return treeMenuAllowAccesss;
    }
}
